package main

import (
	"embed"
	"flag"
	"io"
	"io/fs"
	"net/http"

	"file-view/backend"

	"github.com/gin-gonic/gin"
)

//go:embed packages/front/dist/*
var staticFS embed.FS

var (
	pluginDir string // 插件地址
	address   string
)

func main() {
	flag.StringVar(&pluginDir, "plugin", "./plugins/", "plugin directory")
	flag.StringVar(&address, "address", ":8080", "address")
	flag.Parse()

	router := gin.Default()
	// router.Use(gzip.Gzip(gzip.DefaultCompression))

	buildInController := backend.BuildInController{}
	initRouter(router, &buildInController, &backend.Router{}, &backend.FileController{})

	// 去掉 "packages/front/dist" 前缀，得到干净的 FS
	fsys, err := fs.Sub(staticFS, "packages/front/dist")
	if err != nil {
		panic(err)
	}

	// 用 http.FS 包装，并挂载到根路径
	router.Static("/plugins", pluginDir)
	assetsFS, err := fs.Sub(staticFS, "packages/front/dist/assets")
	if err != nil {
		panic(err)
	}
	router.StaticFS("/assets", http.FS(assetsFS))
	router.GET("/vite.svg", func(c *gin.Context) {
		f, err := fsys.Open("vite.svg")
		if err != nil {
			c.Status(404)
			return
		}
		defer f.Close()
		c.Header("Content-Type", "image/x-icon")
		io.Copy(c.Writer, f)
	})

	router.NoRoute(func(c *gin.Context) {
		if c.Request.Method == "GET" {
			// 假设你的主页面是 embed 到 fsys 中的 index.html
			f, err := fsys.Open("index.html")
			if err != nil {
				c.Status(404)
				return
			}
			defer f.Close()
			c.Header("Content-Type", "text/html; charset=utf-8")
			c.Status(http.StatusOK)
			io.Copy(c.Writer, f)
		} else {
			c.Status(404)
		}
	})

	loadedPlugins, err := LoadPlugins(router, pluginDir)
	if err != nil {
		panic(err)
	}
	buildInController.SetPluginInfo(loadedPlugins)

	err = router.Run(address)
	if err != nil {
		panic(err)
	}
}
